import 'mui-player/dist/mui-player.min.css'
// @ts-ignore
import MuiPlayer from 'mui-player'
import {decoderConfig, ParseConfigParams} from "./DecoderConfig";

export interface HeadControl {
  slot: string; // 对应定义的 slot 值
  click?: (e: Event) => void; // 按钮点击事件回调
  style?: CSSStyleDeclaration; // 自定义添加控件样式 上面添加一个 // @ts-ignore 把错误忽略
}

export interface FooterControl extends HeadControl{
  position?: 'left' | 'right'; // 显示的位置，可选 left、right
  tooltip?: string ; // 鼠标悬浮在控件上显示的文字提示
  oftenShow?: boolean ; // 是否常显示。默认为false，在 mobile 环境下竖屏状态下隐藏，pc环境判下视频容器小于500px时隐藏
}

export interface RightSidebar {
  slot:string, // 对应定义的 slot 值
  width?:string|number // 侧栏宽度，string | number
}

export interface MuiPlayerConfig {
  live?: boolean;
  autoplay?: boolean;
  parse?: any;
  loop?: boolean;
  preload?: 'none' | 'metadata' | 'auto'; // 如果 autoplay=true，则忽略该属性
  custom?: {
    headControls?: HeadControl[],
    footerControls?: FooterControl[],
    rightSidebar?: RightSidebar[],
  }
}

export type MuiPlayerResultNowDecoder = 'auto' | '.mp4' | '.hls' | '.flv' | '.mpd' | string
export type MuiPlayerResultEvents = 'error' | 'destroy' | 'pagefull-change' | 'ready' | string

export interface MuiPlayerResult {
  containerEl: HTMLElement;
  nowDecoder: MuiPlayerResultNowDecoder;

  removeControls(className: string[]): void;

  reloadUrl(url: string): void;//指定一个视频地址重新加载资源，不传参则默认重新加载， 这个要默认给一个地址才能播放
  destroy(): void;//销毁视频播放器
  on(event: MuiPlayerResultEvents, eventHandle: () => void): void;

  sendError(errMes: string): void;

  specifyTheCodec(decoderName: MuiPlayerResultNowDecoder): void  // 手动指定解码器

  video(): HTMLVideoElement;
  toggleControls(show:boolean):void;//主动 隐藏/显示 播放器 controls。参数可传递一个布尔值用可强制显示或隐藏
  showRightSidebar(slotName:string):void; // 弹出自定义右侧栏窗口
}

MuiPlayer.prototype.removeControls = function (className: string[]) { // 根据class移除控制器
  const self = this as MuiPlayerResult
  className.forEach(item => {
    Array.from(self.containerEl.getElementsByClassName(item)).forEach(i => {
      i.remove()
    })
  })
}

MuiPlayer.prototype.specifyTheCodec = function (decoder: MuiPlayerResultNowDecoder) { // 手动指定解码器
  const self = this as MuiPlayerResult
  self.nowDecoder = decoder
}


export function getMuiPlayer(el: HTMLElement, src: string, otherConfig?: MuiPlayerConfig, decoderConfigParam?: ParseConfigParams): MuiPlayerResult {
  if (!decoderConfigParam) {
    decoderConfigParam = {
      otherDecoders: []
    }
  }
  const result: MuiPlayerResult = new MuiPlayer({
    ...otherConfig,
    container: el,
    src,
    parse: {
      customKernel: decoderConfig(decoderConfigParam)
    }
  })
  result.containerEl = el
  result.nowDecoder = 'auto'
  decoderConfigParam.muiPlayer = result
  return result
}
